package com.movie.controller;

import com.movie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 管理员数据统计控制器
 */
@RestController
@RequestMapping("/api/admin/stats")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
@PreAuthorize("hasRole('ADMIN')")
public class AdminStatsController {

    @Autowired
    private UserService userService;

    /**
     * 获取总体统计数据
     * @return 总体统计信息
     */
    @GetMapping("/overview")
    public ResponseEntity<Map<String, Object>> getOverviewStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 用户统计
            int totalUsers = userService.getUserCount();
            stats.put("totalUsers", totalUsers);
            
            // 模拟其他统计数据
            stats.put("totalMovies", 25);
            stats.put("totalOrders", 1580);
            stats.put("totalRevenue", new BigDecimal("156800.50"));
            stats.put("todayOrders", 45);
            stats.put("todayRevenue", new BigDecimal("4580.00"));
            stats.put("activeUsers", Math.max(1, totalUsers - 5)); // 活跃用户数
            
            return ResponseEntity.ok(stats);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取用户增长趋势数据
     * @return 用户增长趋势
     */
    @GetMapping("/user-growth")
    public ResponseEntity<Map<String, Object>> getUserGrowthStats() {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> growthData = new ArrayList<>();
            
            // 模拟最近7天的用户增长数据
            LocalDate today = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
            
            for (int i = 6; i >= 0; i--) {
                LocalDate date = today.minusDays(i);
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", date.format(formatter));
                dayData.put("newUsers", (int)(Math.random() * 20) + 5); // 5-25个新用户
                dayData.put("activeUsers", (int)(Math.random() * 100) + 50); // 50-150活跃用户
                growthData.add(dayData);
            }
            
            result.put("growthData", growthData);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取用户增长数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取收入统计数据
     * @return 收入统计
     */
    @GetMapping("/revenue")
    public ResponseEntity<Map<String, Object>> getRevenueStats() {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> revenueData = new ArrayList<>();
            
            // 模拟最近7天的收入数据
            LocalDate today = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
            
            for (int i = 6; i >= 0; i--) {
                LocalDate date = today.minusDays(i);
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", date.format(formatter));
                dayData.put("revenue", (Math.random() * 5000) + 2000); // 2000-7000元收入
                dayData.put("orders", (int)(Math.random() * 50) + 20); // 20-70个订单
                revenueData.add(dayData);
            }
            
            result.put("revenueData", revenueData);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取收入数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取热门电影排行
     * @return 热门电影数据
     */
    @GetMapping("/popular-movies")
    public ResponseEntity<Map<String, Object>> getPopularMovies() {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> moviesData = new ArrayList<>();
            
            // 模拟热门电影数据
            String[] movieTitles = {"沙丘2", "死侍与金刚狼", "花月杀手", "奥本海默", "心灵捕手2"};
            for (int i = 0; i < movieTitles.length; i++) {
                Map<String, Object> movie = new HashMap<>();
                movie.put("title", movieTitles[i]);
                movie.put("ticketsSold", (int)(Math.random() * 500) + 200);
                movie.put("revenue", (Math.random() * 50000) + 20000);
                movie.put("rating", Math.round((Math.random() * 2 + 8) * 10) / 10.0); // 8.0-10.0评分
                moviesData.add(movie);
            }
            
            result.put("popularMovies", moviesData);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取热门电影数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取用户分布统计
     * @return 用户分布数据
     */
    @GetMapping("/user-distribution")
    public ResponseEntity<Map<String, Object>> getUserDistribution() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 模拟用户年龄分布
            List<Map<String, Object>> ageDistribution = new ArrayList<>();
            String[] ageGroups = {"18-25", "26-35", "36-45", "46-55", "55+"};
            int[] ageCounts = {35, 45, 25, 15, 8}; // 百分比
            
            for (int i = 0; i < ageGroups.length; i++) {
                Map<String, Object> ageData = new HashMap<>();
                ageData.put("ageGroup", ageGroups[i]);
                ageData.put("count", ageCounts[i]);
                ageDistribution.add(ageData);
            }
            
            // 模拟用户地区分布
            List<Map<String, Object>> regionDistribution = new ArrayList<>();
            String[] regions = {"北京", "上海", "广州", "深圳", "杭州", "其他"};
            int[] regionCounts = {25, 20, 15, 12, 10, 18}; // 百分比
            
            for (int i = 0; i < regions.length; i++) {
                Map<String, Object> regionData = new HashMap<>();
                regionData.put("region", regions[i]);
                regionData.put("count", regionCounts[i]);
                regionDistribution.add(regionData);
            }
            
            result.put("ageDistribution", ageDistribution);
            result.put("regionDistribution", regionDistribution);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取用户分布数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
} 